package com.kanshu.basictest.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import androidx.annotation.Nullable;
import android.util.Log;

import com.kanshu.basictest.BookManager;
import com.kanshu.basictest.IBookShelfChangedListener;
import com.kanshu.basictest.model.ipc.Book;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

public class BookManagerService extends Service {

    private static final String TAG = "BookManagerService";

    private List<Book> bookshelf = new CopyOnWriteArrayList<>();

    //private CopyOnWriteArrayList<IBookShelfChangedListener> mBookshelfListeners = new CopyOnWriteArrayList<>();
    private RemoteCallbackList<IBookShelfChangedListener> mBookshelfListeners = new RemoteCallbackList<>();

    private AtomicBoolean mIsServiceDestoryed = new AtomicBoolean(false);

    private BookManager.Stub mBinder = new BookManager.Stub() {
        @Override
        public void addBook(Book newBook) throws RemoteException {
            //运行在服务端的Binder线程池中的某条线程上
            Log.i(TAG, "addBook: 当前线程：" + Thread.currentThread().getName());//Binder_n
            bookshelf.add(newBook);

        }

        @Override
        public List<Book> getBookList() throws RemoteException {
            //运行在服务端的Binder线程池中的某条线程上
            Log.i(TAG, "getBookList: 当前线程：" + Thread.currentThread().getName());//Binder_n
            return bookshelf;
        }

        @Override
        public void registerListener(IBookShelfChangedListener ls) throws RemoteException {
            //运行在服务端的Binder线程池中的某条线程上
            Log.i(TAG, "registerListener: 当前线程：" + Thread.currentThread().getName());//Binder_n
            if (mBookshelfListeners.register(ls))
                Log.i(TAG, "registerListener: 监听注册成功！");
            else
                Log.i(TAG, "registerListener: 监听注册失败！");
            Log.i(TAG, "registerListener: 当前注册监听的数量：" + mBookshelfListeners.getRegisteredCallbackCount());
        }

        @Override
        public void unRegisterListener(IBookShelfChangedListener ls) throws RemoteException {
            //运行在服务端的Binder线程池中的某条线程上
            Log.i(TAG, "unRegisterListener: 当前线程：" + Thread.currentThread().getName());//Binder_n
            if (mBookshelfListeners.unregister(ls))
                Log.i(TAG, "unRegisterListener: 监听注销成功！");
            else
                Log.i(TAG, "registerListener: 监听注销失败！");

            Log.i(TAG, "unRegisterListener: 当前注册监听的数量：" + mBookshelfListeners.getRegisteredCallbackCount());
        }

       /*
        //此种方法无法注销监听
        @Override
        public void registerListener(IBookShelfChangedListener ls) throws RemoteException {
            if (!mBookshelfListeners.contains(ls)) {
                mBookshelfListeners.add(ls);
            } else {
                Log.i(TAG, "registerListener:重复注册监听！");
            }
            Log.i(TAG, "registerListener：" + mBookshelfListeners.size());
        }

        @Override
        public void unRegisterListener(IBookShelfChangedListener ls) throws RemoteException {
            boolean removed = mBookshelfListeners.remove(ls);
            if (removed) {
                Log.i(TAG, "unRegisterListener:注销监听！");
            } else {
                Log.i(TAG, "unRegisterListener:没找到监听，无法注销！");
            }
            Log.i(TAG, "unRegisterListener:当前已注册监听客户端的数量：" + mBookshelfListeners.size());
        }*/
    };

    @Override
    public void onCreate() {
        super.onCreate();
        bookshelf.add(new Book("001", "李刚"));
        bookshelf.add(new Book("002", "张曼玉"));
        new Thread(new ServiceWorker()).start();

    }

    @Override
    public void onDestroy() {
        mIsServiceDestoryed.set(true);
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    //新书上架后，通知订阅的客户
    private void noticeClient(Book newBook) throws RemoteException {
        //此方法运行在 新建的线程
        Log.i(TAG, "noticeClient: 当前线程：" + Thread.currentThread().getName());//Thread-188
        int COUNT = mBookshelfListeners.beginBroadcast();
        for (int i = 0; i < COUNT; i++) {
            mBookshelfListeners.getBroadcastItem(i).onNewBookAdded(newBook);
        }
        mBookshelfListeners.finishBroadcast();
    }

    private class ServiceWorker implements Runnable {

        @Override
        public void run() {

            while (!mIsServiceDestoryed.get()) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                String id = String.valueOf(bookshelf.size() + 1);
                String name = "Book#".concat(id);
                Book newBook = new Book(id, name);

                //将新书添加至书架
                if (bookshelf.add(newBook)) {
                    try {
                        noticeClient(newBook);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.i(TAG, "run: 新书添加失败！");
                }
            }
        }
    }


}
